'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Send, Mic, Paperclip, Smile, Square } from 'lucide-react';

interface ChatInputProps {
  onSendMessage: (content: string) => void;
  disabled?: boolean;
  placeholder?: string;
  maxLength?: number;
  showAttachment?: boolean;
  showVoice?: boolean;
  showEmoji?: boolean;
  isGenerating?: boolean;
  onStopGeneration?: () => void;
  initialValue?: string;
}

export function ChatInput({
  onSendMessage,
  disabled = false,
  placeholder = "💬 输入你的问题，我来帮你解答...",
  maxLength = 2000,
  showAttachment = true,
  showVoice = true,
  showEmoji = true,
  isGenerating = false,
  onStopGeneration,
  initialValue = ''
}: ChatInputProps) {
  const [inputValue, setInputValue] = useState(initialValue);
  const [isComposing, setIsComposing] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // 当initialValue变化时，更新inputValue
  useEffect(() => {
    if (initialValue && initialValue !== inputValue) {
      setInputValue(initialValue);
    }
  }, [initialValue]);

  // 自动调整文本框高度
  useEffect(() => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;
    }
  }, [inputValue]);

  const handleSend = () => {
    const content = inputValue.trim();
    if (!content || disabled || isGenerating) return;

    onSendMessage(content);
    setInputValue('');
    
    // 重置文本框高度
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey && !isComposing) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleStopGeneration = () => {
    if (onStopGeneration) {
      onStopGeneration();
    }
  };

  const canSend = inputValue.trim().length > 0 && !disabled && !isGenerating;

  return (
    <div className="bg-white border border-blue-200 rounded-xl p-3 md:p-4 shadow-sm">
      {/* 输入区域 */}
      <div className="flex items-end gap-2 md:gap-3">
        {/* 文本输入框 */}
        <div className="flex-1 relative">
          <Textarea
            ref={textareaRef}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyDown={handleKeyDown}
            onCompositionStart={() => setIsComposing(true)}
            onCompositionEnd={() => setIsComposing(false)}
            placeholder={placeholder}
            disabled={disabled}
            maxLength={maxLength}
            className="min-h-[48px] max-h-[120px] resize-none border-2 border-blue-200 focus:border-blue-500 rounded-lg bg-white text-gray-900 placeholder:text-blue-400 pr-12"
            style={{ paddingRight: showEmoji ? '48px' : '12px' }}
          />
          
          {/* 表情按钮 */}
          {false && (
            <Button
              size="sm"
              variant="ghost"
              className="absolute right-2 bottom-2 text-blue-400 hover:text-blue-600 h-8 w-8 p-0"
              disabled={disabled}
            >
              <Smile className="w-4 h-4" />
            </Button>
          )}
        </div>

        {/* 附件按钮 - 移动端隐藏 */}
        {false && (
          <Button
            variant="outline"
            size="sm"
            className="hidden md:flex h-12 px-3 border-2 border-blue-200 hover:border-blue-400 hover:text-blue-600 text-blue-500"
            disabled={disabled}
          >
            <Paperclip className="w-4 h-4" />
          </Button>
        )}

        {/* 语音按钮 - 移动端隐藏 */}
        {false && (
          <Button
            variant="outline"
            size="sm"
            className="hidden md:flex h-12 px-3 border-2 border-blue-200 hover:border-blue-400 hover:text-blue-600 text-blue-500"
            disabled={disabled}
          >
            <Mic className="w-4 h-4" />
          </Button>
        )}

        {/* 发送/停止按钮 */}
        {isGenerating ? (
          <Button
            onClick={handleStopGeneration}
            className="h-12 px-6 bg-red-500 hover:bg-red-600 text-white transition-all duration-300"
          >
            <Square className="w-4 h-4 mr-2" />
            停止
          </Button>
        ) : (
          <Button
            onClick={handleSend}
            disabled={!canSend}
            className="h-12 px-6 bg-blue-500 hover:bg-blue-600 text-white transition-all duration-300 hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
          >
            <Send className="w-4 h-4 mr-2" />
            发送
          </Button>
        )}
      </div>



      {/* 快捷操作提示 */}
      <div className="mt-2 text-center hidden md:block">
        <p className="text-xs text-gray-500">
          按 Enter 发送，Shift + Enter 换行, ⚠️ 内容由AI生成，请核查重要信息
        </p>
      </div>

    </div>
  );
}

// 快速问题组件
interface QuickQuestionsProps {
  questions: Array<{
    text: string;
    emoji: string;
    category: string;
  }>;
  onQuestionClick: (question: string) => void;
  disabled?: boolean;
}

export function QuickQuestions({ questions, onQuestionClick, disabled = false }: QuickQuestionsProps) {
  return (
    <div className="bg-white border-x border-blue-200 px-4 py-3">
      <div className="flex items-center gap-2 mb-3">
        <div className="w-4 h-4 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full"></div>
        <h3 className="text-sm font-semibold text-blue-900">快速提问</h3>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
        {questions.slice(0, 6).map((question, index) => (
          <Button
            key={index}
            variant="outline"
            onClick={() => onQuestionClick(question.text)}
            disabled={disabled}
            className="h-auto p-3 text-left justify-start border border-blue-200 hover:border-blue-400 hover:bg-blue-50 transition-all text-xs"
          >
            <div className="flex items-center gap-2">
              <span className="text-sm">{question.emoji}</span>
              <div className="flex flex-col items-start">
                <span className="font-medium text-blue-900 truncate">{question.text}</span>
                <span className="text-xs text-blue-600">{question.category}</span>
              </div>
            </div>
          </Button>
        ))}
      </div>
    </div>
  );
}
